package study.springboot.mvc.support.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import study.springboot.mvc.support.interceptor.CustomHandlerInterceptor;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Configuration
public class WebMvcCfg implements WebMvcConfigurer {



    @Autowired
    private CustomHandlerInterceptor customHandlerInterceptor;


    /**
     * （★）拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(customHandlerInterceptor)
                .addPathPatterns("/**");
    }

    /**
     * （★）跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "DELETE", "OPTIONS") //允许跨域的提交方法
                .allowedOrigins("*")    //允许跨域请求的域名
                .allowedHeaders("*")    //允许跨域请求的头部
                .allowCredentials(true) //是否允许证书不再默认开启
                .maxAge(3600);          //
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        //是否允许证书不再默认开启
        corsConfig.setAllowCredentials(true);
        //允许跨域请求的域名
        corsConfig.addAllowedOrigin("*");
        //允许跨域的提交方法
        corsConfig.addAllowedMethod("POST, GET, OPTIONS, DELETE");
        //允许跨域的头部
        corsConfig.addAllowedHeader("*");
        //
        corsConfig.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(-100);
        return bean;
    }
}
